package com.hoshiicloud.saleorder.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.QueryException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.saleorder.entity.OrderStatus;
import com.hoshiicloud.saleorder.feign.IdGeneratorService;
import com.hoshiicloud.saleorder.mapper.OrderStatusMapper;
import com.hoshiicloud.saleorder.service.OrderStatusService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 订单状态记录 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-03
 */
@Slf4j
@Service
public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, OrderStatus> implements
        OrderStatusService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * @param id
     * @return com.hoshiicloud.saleorder.entity.OrderStatus
     * @description: 根据id查询订单状态记录
     */
    @Override
    @Cacheable(cacheNames = "OrderStatus", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "销售订单-订单状态记录-查询订单状态记录 ")
    public OrderStatus getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * @param entity
     * @return boolean
     * @description: 新增订单状态记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderStatus", allEntries = true)
    @Logable(authName = "销售订单-订单状态记录-新增订单状态记录")
    public boolean save(OrderStatus entity) {

        return Optional.ofNullable(entity).map(orderStatus -> {
            String id = idGeneratorService.queryGeneratorId();
            log.error("{}", id);

            if (StrUtil.isBlank(id)) {
                log.error("id生成异常");
                throw new ServiceException(CommonError.error("网络开小差啦~, 请重新尝试"));
            }

            orderStatus.setId(Long.parseLong(id));
            orderStatus.setCreatedTime(LocalDateTime.now());

            int row = baseMapper.insert(orderStatus);
            if (row <= 0) {
                log.error("新增订单状态记录失败");
                throw new ServiceException(CommonError.error("新增订单状态记录失败"));
            }
            return true;
        }).orElseThrow(() -> new ServiceException(CommonError.error("新增订单状态记录失败，保存对象为空")));
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改订单状态记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderStatus", allEntries = true)
    @Logable(authName = "销售订单-订单状态记录管理-修改订单状态记录")
    public boolean updateById(OrderStatus entity) {

        return Optional.ofNullable(entity).map(orderStatus -> {
            entity.setUpdatedTime(LocalDateTime.now());
            int row = baseMapper.updateById(entity);
            if (row <= 0) {
                throw new ServiceException(CommonError.error("修改订单状态记录失败"));
            }
            return true;
        }).orElseThrow(() -> new ServiceException(CommonError.error("修改订单状态记录失败，保存对象为空")));
    }

    /**
     * @param key
     * @return IPage
     * @description: 分页查询订单状态记录
     */
    @Override
    @Logable(authName = "销售订单-订单状态记录管理-分页查询订单状态记录")
    @Cacheable(cacheNames = "OrderStatus", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+ T(com.hoshiicloud.common.utils.DigestUtils).md5(#key)")
    public IPage<OrderStatus> page(IPage<OrderStatus> page, Wrapper<OrderStatus> queryWrapper, String key) {
        try {

            return baseMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            log.error("分页查询订单状态记录异常 {}", e.getMessage());
            throw new ServiceException("分页查询订单状态记录异常");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderStatus", allEntries = true)
    @Logable(authName = "销售订单-订单状态记录管理-删除订单状态记录")
    public boolean deleteById(Long id) {
        OrderStatus entity = this.getById(id);

        return Optional.ofNullable(entity).map(orderStatus -> {
            orderStatus.setUpdatedTime(LocalDateTime.now()).setDeleted(1);
            int row = baseMapper.updateById(orderStatus);
            if (row <= 0) {
                throw new ServiceException(CommonError.error("删除订单状态记录失败"));
            }
            return true;
        }).orElseThrow(() -> {
            log.error("删除订单状态记录异常，无法找到订单状态记录记录");
            return new QueryException("删除订单状态记录异常，无法找到订单状态记录记录");
        });

    }

    @Override
    @Cacheable(cacheNames = "OrderStatus", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "销售订单-订单状态记录管理-根据id集合查询订单状态记录")
    public List<OrderStatus> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }
}
